import md5 from 'md5'
import { SYSTEM } from '../config'

//config配置
class getsql{

    constructor(){
        
    }

    /*  组装sql  --- SELECT
        selectArr:需要查询的字段    [name,age]
        table:查询的表
        acctoArr: 查询的where条件   [{key:'name',val:'wangwei'}]
        orderByDesc:boolean,      是否desc排序
        orderByField:             排序字段
        isCOUNT: 是否查询总数
        LIMIT: {pageSize:10,pageNo:1}
    */
    getSelectSql(json={}){
        let sql           = 'select ';
        let selectArr     = json.selectArr || []
        let acctoArr      = json.acctoArr || []
        let acctoArrCopy  =[]
        let orderByDesc   = json.orderByDesc
        let orderByField  = json.orderByField
        let isCOUNT       = json.isCOUNT?true:false
        let LIMIT         = json.LIMIT || {}
        
        //---------- 处理COUNT -------------------------------
        if(isCOUNT){
            //查询total 总数
            sql += ` COUNT(*) from ${json.table} `
        }else{
            //查询数据列表
            if(selectArr.length){
                sql += `${selectArr.join(',')} from ${json.table} `
            }else{
                sql += `* from ${json.table} `
            }
        }

        //---------- 处理WHERER -------------------------------
        for(let i=0,len=acctoArr.length;i<len;i++){
            if(acctoArr[i].val + ''){
                acctoArrCopy.push(acctoArr[i]);
            }
        };
        if(acctoArrCopy.length){
            let str    = '';
            if(acctoArrCopy.length == 1){
                str += `${acctoArrCopy[0].key}='${acctoArrCopy[0].val}' `
            }else{
                for(let i=0,len=acctoArrCopy.length;i<len;i++){
                    if(i == acctoArrCopy.length-1){
                        str += `${acctoArrCopy[i].key}='${acctoArrCopy[i].val}' `
                    }else{
                        str += `${acctoArrCopy[i].key}='${acctoArrCopy[i].val}' and `
                    }
                }
            };
            sql += `where ${str} `;
        }

        //----------- 处理ORDER BY ------------------------------
        if(orderByDesc&&orderByField){
            sql += `order by ${orderByField} desc `
        }else if(!orderByDesc&&orderByField){
            sql += `order by ${orderByField} `
        }

        //----------- 处理limit ---------------------------------
        if(LIMIT.pageNo){
            let begin = 0;
            if(LIMIT.pageNo == 1){
                begin = 0;
            }else{
                begin = (parseInt(LIMIT.pageNo) - 1) * parseInt(LIMIT.pageSize);
            }

            sql += ` LIMIT ${begin},${LIMIT.pageSize} `
        }

        return sql;
    };

    /* 组装sql  --- 
        
    */
}

module.exports = new getsql();



